function creatheadimg(headimgurl) {
    var headimgshadowwidth = (window.innerWidth-300)/2;
    var headimgclipwidth = window.innerWidth;
    var headimg = new Image();
    headimg.src = headimgurl;
    headimg.onload = function () {
        if (headimg.width>headimg.height){
            var transwidth = headimg.width/headimg.height*300;
            var left = (headimgclipwidth-transwidth)/2;
            var headimghtml = Crownapp.HeadimgcontainerhorTemplate({left:left,swidth:headimgshadowwidth,width:headimgclipwidth,src:headimg.src});
            $$('.headimg-container').html(headimghtml);
            var poslimitleft = headimgshadowwidth+300-transwidth;
            var poslimitright = headimgshadowwidth;
            $$('.headimg').on('touchstart',function (e) {
                var touchpos = e.touches[0].pageX;
                $$(this).data('touchpos',touchpos);
            });
            $$('.headimg').on('touchmove',function (e) {
                var touchposstart = parseFloat($$(this).data('touchpos'));
                var touchposend = e.touches[0].pageX;
                var curpos = parseFloat($$(this).data('pos'));
                var topos = curpos+(touchposend-touchposstart)/10;
                if (topos<poslimitleft){
                    topos=poslimitleft;
                }else if(topos>poslimitright){
                    topos=poslimitright;
                }
                $$(this).css('left',topos+'px');
                $$(this).data('pos',topos);
            });
        }else if(headimg.width<headimg.height){
            var transHeight = headimg.height/headimg.width*300;
            var top = (450-transHeight)/2;
            var headimghtml = Crownapp.HeadimgcontainerverTemplate({top:top,swidth:headimgshadowwidth,src:headimg.src});
            $$('.headimg-container').html(headimghtml);
            var poslimittop = 375-transHeight;
            var poslimitbottom = 75;
            $$('.headimg').on('touchstart',function (e) {
                var touchpos = e.touches[0].pageY;
                $$(this).data('touchpos',touchpos);
            });
            $$('.headimg').on('touchmove',function (e) {
                var touchposstart = parseFloat($$(this).data('touchpos'));
                var touchposend = e.touches[0].pageY;
                var curpos = parseFloat($$(this).data('pos'));
                var topos = curpos+(touchposend-touchposstart)/10;
                // console.log(touchposstart,touchposend,topos);
                if (topos<poslimittop){
                    topos=poslimittop;
                }else if(topos>poslimitbottom){
                    topos=poslimitbottom;
                }
                $$(this).css('top',topos+'px');
                $$(this).data('pos',topos);
            });
        }else{
            var headimghtml = Crownapp.HeadimgcontainerhorTemplate({left:headimgshadowwidth,swidth:headimgshadowwidth,width:headimgclipwidth,src:headimg.src});
            $$('.headimg-container').html(headimghtml);
        }
    };
    return headimg;
}
function uploadimg() {
    wx.chooseImage({
        counts:1,
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
            var localids = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
            wx.getLocalImgData({
                localId: localids[0], // 图片的localID
                success: function (res) {
                    headimgurl = res.localData; // localData是图片的base64数据，可以用img标签显示
                    headimg = creatheadimg(headimgurl);
                }
            })
        }
    });
}
function getheadimg() {
    $$.ajax({
        contentType:'OPTIONS',
        crossDomain:true,
        method:'GET',
        async:false,
        url:"http://api.nldou.com/act/crown/getHeadImg",
        data:{},
        dataType:'json',
        xhrFields:{"withCredentials":true},
        success:function (res) {
            //console.log('用户登陆',res);
            if (res.code == 0){
                window.location.href = "http://api.nldou.com/act/crown/login";
            } else {
                headimgurl = res.data;
                headimg = creatheadimg(headimgurl);
            }
        }
    });
}

var $$ = Dom7;
var ApiUrl = 'http://api.nldou.com/';
var initjssdk_url = ApiUrl+'weixinapi/init_wx_jsapi';
/****微信js sdk初始化****/
$$.ajax({
    url:initjssdk_url,
    method:"GET",
    data: {fromUrl:window.location.href},
    dataType:'json',
    success: function (res) {
        //console.log('初始化jssdk',res);
        if(res.code==1){
            wx.config({
                debug: false,
                appId: res.data.appid,
                timestamp: res.data.timestamp,
                nonceStr: res.data.nonceStr,
                signature: res.data.signature,
                jsApiList: ['onMenuShareTimeline','onMenuShareAppMessage','hideMenuItems','chooseImage'
                    ,'uploadImage','getLocalImgData']
            });
        }
    }
});
wx.ready(function () {
    wx.hideMenuItems({
        menuList: ['menuItem:share:qq','menuItem:share:weiboApp','menuItem:share:facebook','menuItem:share:QZone',
            'menuItem:copyUrl','menuItem:openWithQQBrowser','menuItem:openWithSafari']
    });
    wx.onMenuShareTimeline({
        title: '女王节，我为自己加冕',
        link: 'http://api.nldou.com/act/crown/login',
        imgUrl: 'http://wap.nldou.com/crown/img/sharebg.jpg',
        success: function () {}
    });
    wx.onMenuShareAppMessage({
        title: '女王节，我为自己加冕',
        desc: '不要叫我大王，叫我女王大人',
        link: 'http://api.nldou.com/act/crown/login',
        imgUrl: 'http://wap.nldou.com/crown/img/sharebg.jpg',
        type: 'link',
        success: function () {}
    });
});
wx.error(function (res) {
});

/****Initialize your app****/
var Crownapp = new Framework7({
    animateNavBackIcon: true,
    template7Pages:true,
    modalButtonOk:'知道了',
    modalButtonCancel:'取消'
});

/****Add view****/
var mainView = Crownapp.addView('.view-main', {
    dynamicNavbar: true
});

Crownapp.HeadimgcontainerhorTemplate = Template7.compile($$('script#Headimgcontainerhor').html());
Crownapp.HeadimgcontainerverTemplate = Template7.compile($$('script#Headimgcontainerver').html());

// var headimgurl = 'img/text1.jpg';
// var headimg = creatheadimg(headimgurl);
var headimg,headimgurl;
getheadimg();

//阻止微信下拉露黑底
$$('body').on('touchmove',function (e) {
    e.preventDefault();
});
$$(document).on('click','.to-upload-image',function(){
    uploadimg();
});
$$(document).on('click','.to-add-crown',function(){
    var pos = parseFloat($$('.headimg').data('pos'));
    var shaw = (window.innerWidth-300)/2;
    var type = $$('.headimg').data('type');
    //console.log(pos);
    var sx,sy,sWidth,sHeight,trans;
    switch (type){
        case 'hor':
            trans = headimg.width/headimg.height*300;
            sx = Math.ceil((shaw-pos)/trans*headimg.width);
            sy = 0;
            sWidth = headimg.height;
            sHeight = headimg.height;
            break;
        case 'ver':
            trans = headimg.height/headimg.width*300;
            sx = 0;
            sy = Math.ceil((75-pos)/trans*headimg.height);
            sWidth = headimg.width;
            sHeight = headimg.width;
            break;

    }
    // console.log(sx,sy,sWidth,sHeight,type);
    mainView.router.load({url:'addcrown.html',context:{sx:sx,sy:sy,sw:sWidth,sh:sHeight}});
});

Crownapp.onPageInit('Addcrown',function(){
    //选图区域
    var sx = $$('#Addcrown').data('sx');
    var sy = $$('#Addcrown').data('sy');
    var sw = $$('#Addcrown').data('sw');
    var sh = $$('#Addcrown').data('sh');
    var stage1 = document.getElementById('stage1');
    if (stage1.getContext){
        var ctx1 = stage1.getContext('2d');
        var headimgcan = new Image();
        headimgcan.src = headimgurl;
        headimgcan.onload = function () {
            ctx1.drawImage(headimgcan,sx,sy,sw,sh,0,0,300,300);
        };

        var ori = new Object();
        ori.x = (window.innerWidth-300)/2;
        ori.y = 75;
        var pos0 = new Object();//圆心初始坐标
        pos0.x = ori.x + 50 + 25;
        pos0.y = ori.y + 50 + 25;
        var pos00 = new Object();//圆心坐标
        pos00.x = ori.x + 50 + 25;
        pos00.y = ori.y + 50 + 25;
        var pos1 = {x:0,y:0};//触点位置
        var mod0 = Math.sqrt(Math.pow(25,2)*2);//初始半径
        var rot = 0;//旋转角度
        var scale = 1;//缩放比例
        var translate = {x:0,y:0};//平移坐标
        var crown = $$('.crown-icon-wrap');
        // console.log(pos0,pos00);

        $$(document).on('touchmove','.crown-icon-trans-btn',function (e) {
            pos1.x = e.touches[0].pageX;
            pos1.y = e.touches[0].pageY;
            var dx = pos1.x-pos00.x;
            var dy = pos1.y-pos00.y;
            var mod = Math.sqrt(Math.pow(dx,2)+Math.pow(dy,2));
            rot = -Math.acos(dy/mod)/Math.PI*180;
            if (dx<0) rot = -rot;
            scale = mod/mod0;
            if(scale<1) scale = 1;
            $$('.crown-icon-wrap').data('rot',rot);
            $$('.crown-icon-wrap').data('scale',scale);
            crown.transform('translate('+translate.x+'px,'+translate.y+'px) rotate('+rot+'deg) scale('+scale+')');
        });

        $$(document).on('touchmove','.crown-icon-wrap>img',function (e) {
            pos1.x = e.touches[0].pageX;
            pos1.y = e.touches[0].pageY;
            translate.x = pos1.x-pos0.x;
            translate.y = pos1.y-pos0.y;
            pos00.x = pos1.x;
            pos00.y = pos1.y;
            $$('.crown-icon-wrap').data('translatex',translate.x);
            $$('.crown-icon-wrap').data('translatey',translate.y);
            crown.transform('translate('+translate.x+'px,'+translate.y+'px) rotate('+rot+'deg) scale('+scale+')');
        });

        $$(document).on('click','.to-finish',function () {
            var rot = $$('.crown-icon-wrap').data('rot');
            var scale = $$('.crown-icon-wrap').data('scale');
            var translatex = $$('.crown-icon-wrap').data('translatex');
            var translatey = $$('.crown-icon-wrap').data('translatey');
            var crownno = $$('.crown-icon-wrap').data('crown');
            // console.log(sx,sy,sw,sh,rot,scale,translatex,translatey,crownno);
            mainView.router.load({url:'finishcrown.html',context:{rot:rot,scale:scale,transx:translatex,transy:translatey,crownno:crownno}});
        });
    }
    //皇冠选区
    $$('.crown-slide').on('click',function () {
        var crownno = $$(this).data('crown');
        var html = "<img src='img/crown"+crownno+".png' style='width: 100%;height: 100%;'>";
        $$('.crown-icon-wrap>img').remove();
        $$('.crown-icon-wrap').append(html);
        //console.log(crownno);
        $$('.crown-icon-wrap').data('crown',crownno);

    });
    Crownapp.alert('请拖拽皇冠小图标下的《粉红色按钮》实现皇冠的缩放和旋转','');
});
Crownapp.onPageInit('Finishcrown',function(){
    var rot = $$('#Finishcrown').data('rot');
    var scale = $$('#Finishcrown').data('scale');
    var translatex = $$('#Finishcrown').data('translatex');
    var translatey = $$('#Finishcrown').data('translatey');
    var crownno = $$('#Finishcrown').data('crownno');
    //console.log(rot,scale,translatex,translatey,crownno);

    var crownw =Math.ceil(50*scale);
    var crownh =Math.ceil(50*scale);
    // $$('#stage3').css({'height':crownh,'width':crownw});

    var stage2 = document.getElementById('stage2');//最终展示
    var stage1 = document.getElementById('stage1');//背景图
    var stage3 = document.getElementById('stage3');//皇冠图
    if (stage2.getContext&&stage3.getContext) {
        var ctx2 = stage2.getContext('2d');
        var ctx3 = stage3.getContext('2d');

        var crownimg = new Image();
        crownimg.src = 'img/crown'+crownno+'.png';
        crownimg.onload = function () {
            ctx3.translate(150,150);
            ctx3.rotate(rot/180*Math.PI);
            ctx3.translate(-150,-150);
            //console.log(crownw,crownh);
            ctx3.imageSmoothingEnabled = 1;
            ctx3.mozImageSmoothingEnabled = 1;
            ctx3.webkitImageSmoothingEnabled = 1;
            ctx3.msImageSmoothingEnabled = 1;
            ctx3.drawImage(crownimg,150-crownw/2,150-crownh/2,crownw,crownh);
            ctx2.drawImage(stage1,0,0);
            ctx2.drawImage(stage3,translatex-75,translatey-75);

            var imgbase64 = stage2.toDataURL('image/jpeg',1);
            var imghtml = "<img src='"+imgbase64+"' style='width: 300px;'>";
            // alert(imghtml);
            // $$("#stage2").hide();
            $$(".img-container").html(imghtml);
            // console.log(imgdata);
        };
    }
});